import requests     #发送网络请求
import parsel

url = "https://www.che168.com/china/8_10/#pvareaid=100943"

headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
}

response = requests.get(url = url
                        , headers = headers)

response.encoding = 'gbk'       #设置编码

date_html = response.text

#解析数据
selector = parsel.Selector(date_html)

lis = selector.css('.viewlist_ul li')
import pymysql
# 连接数据库
conn = pymysql.connect(host="localhost", user="root", passwd="123456", database="pythondata", charset="utf8")
print('服务器连接成功!')
for li in lis:
    try:
        name = li.css('.card-name::text').get()
        unit = li.css('.cards-unit::text').get()
        kmNumber = unit.split('／')[0]
        years = unit.split('／')[1]
        city = unit.split('／')[2]
        business = unit.split('／')[3]
        price = li.css('.pirce em::text').get()
        yprice = li.css('s::text').get()
        # chajia = yprice - price
        # zhejiu = chajia / yprice
        print(name,kmNumber,years,city,business,price,yprice)
        cursor = conn.cursor()
        try:
            # 一次插入多条记录
            sql = "INSERT INTO test VALUES('"+name+"','"+kmNumber+"','"+years+"','"+city+"','"+business+"','"+price+"','"+yprice[:-1]+"')";
            # print(sql)
            cursor.execute(sql)
            conn.commit()  # 提交更新的数据到数据库
            print('插入成功')
        except Exception as error:  # 插入失败后，抛出异常
            print('插入数据失败')
            print(error)
        # print(name)
    except:
        pass

